package com.bwie.auth.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTUtil;
import com.bwie.auth.remote.SystemRemote;
import com.bwie.auth.service.AuthService;
import com.bwie.auth.sms.SendSmsUtils;
import com.bwie.common.constants.Constants;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.exception.BizException;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.RadomUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

/**
 * @className: AuthServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author:
 * @date:
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SystemRemote systemRemote;
    @Autowired
    private SendSmsUtils sendSmsUtils;

    @Override
    public String login(User user) {
        Boolean b = redisTemplate.hasKey("code" + user.getCode());
        if(!b){
            throw new BizException("验证码失效或者错误");
        }

        Result<User> byTel = systemRemote.findByTel(user);
        if(byTel.getCode()== Constants.ERROR){
            throw new BizException("服务器异常");
        }
        User data = byTel.getData();
        if(ObjectUtils.isEmpty(data)){
            throw new BizException("未注册");
        }

        String s = IdUtil.fastSimpleUUID();
        Map<String, Object> map = new HashMap<String, Object>() {{
            put(JwtConstants.USER_KEY, s);
        }};
        String token = JwtUtils.createToken(map);


        redisTemplate.opsForValue().set(TokenConstants.TOKEN+s,data,60, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public void sendMs(User user) {
        String randomString = RadomUtils.getRandomString(4, 1);
        redisTemplate.opsForValue().set("code"+randomString,1,3,TimeUnit.MINUTES);


        sendSmsUtils.sendSms(user.getTel(), randomString);

    }


}
